<template>
  <div class="text item">
    <el-tree
      :data="permissions"
      show-checkbox
      default-expand-all
      node-key="code"
      ref="tree"
      highlight-current
      :default-checked-keys.sync="checkValues"
      :props="treeProps"
      @check="handleCheck"
      :check-strictly="strictly"
    >
    </el-tree>
  </div>
</template>
<script>
import { getPermissionGroups } from "@/api/permission";
export default {
  data() {
    return {
      permissions: [],
      checkValues: [],
      treeProps: {
        children: "children",
        label: "name",
      },
      strictly: false,
    };
  },
  model: {
    prop: "checkedKeys",
    event: "change",
  },
  methods: {
    getData() {
      this.permissions = [];
      if (!this.role) return;
      getPermissionGroups({ type: 1, skipCount: 0, maxResultCount: 1000 }).then(
        (res) => {
          let groups = res && res.items ? res.items : [];
          this.permissions = this.getPermissionTreeData(groups);
        }
      );
    },
    getPermissionTreeData(groups) {
      let result = [];

      if (!groups || groups.length == 0) return result;

      for (let i = 0; i < groups.length; i++) {
        let group = groups[i];

        let permissionItems = group.items || [];
        let nodes = permissionItems.toTree();
        result = result.concat(nodes);
      }
      return result;
    },
    handleCheck(node, nodeCheckInfo) {
      let checkNodes = this.$refs.tree.getCheckedNodes(false, true);

      let codes = checkNodes.map((x) => x.code);

      this.$emit("change", codes);
    },
  },
  mounted() {
    this.getData();
  },
  watch: {
    checkedKeys: {
      handler(val) {
        if (!this.checkValues || this.checkValues.length == 0) {
          this.checkValues = val;
          this.strictly = false;
        }
      },
    },
  },
  props: {
    checkedKeys: {
      type: Array,
      default: () => [],
    },
    role: {
      type: Object,
      default: () => {},
    },
  },
};
</script>
<style scoped></style>
